%% Author: tangj
%% Created: 2012-9-19
%% Description: TODO: Add description to client
-module(client).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([start/0, stop/0, loop/1]).

-define(HOST, {127, 0, 0, 1}).
-define(PORT, 54321).


%%
%% API Functions
%%

start() ->
	{ok, Socket} = gen_tcp:connect(?HOST, ?PORT, [binary, 
												  {packet, 0}, 
												  {keepalive, true}]),
	%% 开个进程用来接收和发送
	register(?MODULE, Pid = spawn(?MODULE, loop, [Socket])),
	gen_tcp:controlling_process(Socket, Pid).

loop(Socket) ->
	receive
		{tcp, Socket, Bin} ->
			io:format("~p~n", [Bin]),
			loop(Socket);
		{tcp_closed, Socket} ->
			io:format("socket closed~n"),
			gen_tcp:close(Socket);
		Data when is_binary(Data) ->
			io:format("Socket ~p~n", [Socket]),
			ok = gen_tcp:send(Socket, Data),
			loop(Socket);
		stop ->
			io:format("loop end~n"),
			gen_tcp:close(Socket);
		_->
			io:format("please send binary data!~n"),
			loop(Socket)
	after 5000 ->
		ok = gen_tcp:send(Socket, <<0, 4, 10000:8/unit:2>>),
		loop(Socket)
	end.

stop() ->
	?MODULE ! stop.

%%
%% Local Functions
%%

